package com.lew.jlight.web.shiro.util;

import com.lew.jlight.core.util.BeanUtil;
import com.lew.jlight.web.entity.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 序列号工具类
 */
public class SerializeUtil {

    private static Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

    public static Object deserialize(byte[] bytes) {
        Object result = null;
        if (bytes==null || bytes.length==0) {
            return null;
        }
        try {
            ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
                try {
                    result = objectInputStream.readObject();
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException("failed to deserialize object type", ex);
                }
            } catch (Throwable ex) {
                throw new RuntimeException("failed to deserialize", ex);
            }
        } catch (Exception e) {
            logger.error("failed to deserialize", e);
        }
        return result;
    }

    /**
     * 序列化
     */
    public static byte[] serialize(Object object) {
        byte[] result = null;
        if (BeanUtil.isEmpty(object)) {
            return new byte[0];
        }
        if(object instanceof User){
            System.out.println("it is user");
        }
        try {
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            try {
                if (!(object instanceof Serializable)) {
                    throw new IllegalArgumentException(
                           "object must implements the interface of Serializeable");
                }
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
                objectOutputStream.writeObject(object);
                objectOutputStream.flush();
                result = byteStream.toByteArray();
            } catch (Throwable ex) {
                throw new Exception("failed to serialize", ex);
            }
        } catch (Exception ex) {
            logger.error("failed to serialize", ex);
        }
        return result;
    }
}
